package com.hoshiicloud.suppplier.controller;

import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.user.dto.supppiler.*;
import com.hoshiicloud.user.param.supppiler.*;
import com.hoshiicloud.suppplier.feign.IUsersService;
import com.hoshiicloud.suppplier.feign.IdGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:campchen
 * @Date:Created in 下午 02:16 2019/6/20
 * @PACKAGENAME com.hoshiibuy.suppplier.controller
 * @Description
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/suppplier/platformOrganization")
@Api(value = "平台供应商", tags = {"平台供应商聚合服务管理"})
public class PlatformOrganizationController {
    @Autowired
    private IUsersService usersService;

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * 新增供应商
     */
    @PostMapping("/addPlatformOrganization")
    @ApiOperation(value = "平台供应商新增")
    // @Transactional(rollbackFor = Exception.class)
    public Response addPlatformOrganization(@RequestBody AddPlatformOrganizationDTO dto) {
        Response rs;
        /**新增供应商*/
        try {
            rs = usersService.savePlatformOrganization(dto.getPlatOrganizationAddParam());
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商异常" + e.getMessage());
        }
        //获取供应商id 主要供应新增附件使用
        Long organizationId = Long.parseLong(rs.getData().toString());


        /**新增经营类目*/
        List<PlatOrganizationCategoryDTO> listCategory = new ArrayList<>();
        //获得新增经营品类的所有id
        List<Long> categoryIds = new ArrayList<>();
        dto.getListCategory().forEach(platOrganizationCategoryAddParam -> {
            PlatOrganizationCategoryDTO platOrganizationCategoryDTO = null;
            try {
                platOrganizationCategoryDTO = BeanUtils.covertType(platOrganizationCategoryAddParam, PlatOrganizationCategoryDTO.class);
            } catch (Exception e) {
                throw new ServiceException(CommonError.error("转换失败"));
            }
            Long id = Long.parseLong(idGeneratorService.queryGeneratorId());
            platOrganizationCategoryDTO.setId(id);
            listCategory.add(platOrganizationCategoryDTO);
            categoryIds.add(id);
        });
        try {
            rs = usersService.insertCategory4PlatOrganization(listCategory);
            if (rs.getCode() != 200 || rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商经营品类异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商经营品类异常" + e.getMessage());
        }




        /**新增附件*/
        List<PlatOrganizationAttachmentDTO> list=new ArrayList<>();
        //获得新增附件的所有id
        List<Long> ids=new ArrayList<>();
        dto.getListAttachment().forEach(
                platOrganizationAttachmentAddParam->{
                    PlatOrganizationAttachmentDTO platOrganizationAttachmentDTO = null;
                    try {
                        platOrganizationAttachmentDTO = BeanUtils.covertType(platOrganizationAttachmentAddParam, PlatOrganizationAttachmentDTO.class);
                    } catch (Exception e) {
                        throw new ServiceException(CommonError.error("转换失败"));
                    }
                    Long id=Long.parseLong(idGeneratorService.queryGeneratorId());
                    platOrganizationAttachmentDTO.setId(id);
                    platOrganizationAttachmentDTO.setVendorId(organizationId);
                    list.add(platOrganizationAttachmentDTO);
                    ids.add(id);
                }
        );
        try {
            rs=usersService.insertAttach4PlatOrganization(list);
            if (rs.getCode()!=200||rs.getData()==null) {
                throw new ServiceException(rs.getMsg());
            }
        }catch (Exception e){
            log.error("新增供应商附件异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商附件异常" + e.getMessage());
        }

        /**如果存在该租户会员获取其id 如不存在则新增并获取其id  主要为部门员工关联表使用*/
        Response<Member> responseM = usersService.getMemberByMobile(dto.getCompanyId(),dto.getAdminMobile());
        //关联租户会员与内部员工所需id
        if (responseM.getCode()!=200||responseM.getData()==null){
            throw new ServiceException(rs.getMsg());
        }
        //关联租户会员与内部员工所需id
        Long memberId =responseM.getData().getId();


        /**新增系统部  获取其部门id 主要为新增部门会员关联表使用*/
        PlatOrganizationDepartmentesAddParam platOrganizationDepartmentesAddParam = new PlatOrganizationDepartmentesAddParam();
        platOrganizationDepartmentesAddParam.setParentId(0L);
        platOrganizationDepartmentesAddParam.setOrganizationId(organizationId);
        platOrganizationDepartmentesAddParam.setMobile(dto.getAdminMobile());
        platOrganizationDepartmentesAddParam.setName(dto.getPlatOrganizationAddParam().getName());
        platOrganizationDepartmentesAddParam.setCharge("超级管理员");
        try {
            rs = usersService.savePlatformOrganizationDepartmentes(platOrganizationDepartmentesAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门异常" + e.getMessage());
        }

        Long departmentesId = Long.parseLong(rs.getData().toString());


        /**新增平台供应商系统部人员 获得员工id 主要为部门员工关联表使用*/
        PlatOrganizationUsersAddParam platOrganizationUsersAddParam = new PlatOrganizationUsersAddParam();
        platOrganizationUsersAddParam.setMemberId(memberId);
        platOrganizationUsersAddParam.setMobile(dto.getAdminMobile());
        platOrganizationUsersAddParam.setPosition("超级管理员");
        try {
            rs = usersService.savePlatformOrganizationUsers(platOrganizationUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商员工异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商员工异常" + e.getMessage());
        }
        //人员与部门进行关联
        Long userId = Long.parseLong(rs.getData().toString());


        /**新增人员部门关联表*/
        PlatOrganizationDepartmentesUsersAddParam platOrganizationDepartmentesUsersAddParam = new PlatOrganizationDepartmentesUsersAddParam();
        platOrganizationDepartmentesUsersAddParam.setCompanyId(dto.getCompanyId());
        platOrganizationDepartmentesUsersAddParam.setPlatformId(dto.getPlatOrganizationAddParam().getPlatId());
        platOrganizationDepartmentesUsersAddParam.setDepartmentId(departmentesId);
        platOrganizationDepartmentesUsersAddParam.setRole("2");
        platOrganizationDepartmentesUsersAddParam.setEnabled(1);
        platOrganizationDepartmentesUsersAddParam.setUserId(userId);
        platOrganizationDepartmentesUsersAddParam.setCreatedBy("系统自动生成");
        try {
            rs = usersService.savePlatformOrganizationDepartmentesUsers(platOrganizationDepartmentesUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门员工关联表异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门员工关联表异常" + e.getMessage());
        }
        return Response.data("新增成功");
    }

    /**
     * 平台供应商人员新增
     */
    @PostMapping("/savePlatformOrganizationUsers")
    @ApiOperation(value = "新增平台供应商人员")
    @Transactional(rollbackFor = Exception.class)
    public Response savePlatformOrganizationUsers(@RequestBody AddPlatformOrganizationUsersDTO dto) {
        Response rs;
        /**通过电话号码查询member是否存在 存在则返回memberId不存在则新增  平台id  部门id*/
        try {
            rs = usersService.savePlatformOrganizationUsers(dto.getPlatOrganizationUsersAddParam());
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增平台供应商人员异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增平台供应商人员异常" + e.getMessage());
        }
        String userId = rs.getData().toString();
        /**添加人员的同时 添加部门人员关联表*/
        //将信息添加到部门 用户关联表。
        PlatOrganizationDepartmentesUsersAddParam platOrganizationDepartmentesUsersAddParam = new PlatOrganizationDepartmentesUsersAddParam();
        platOrganizationDepartmentesUsersAddParam.setCompanyId(dto.getCompanyId());
        platOrganizationDepartmentesUsersAddParam.setPlatformId(dto.getPlatformId());
        platOrganizationDepartmentesUsersAddParam.setDepartmentId(dto.getDepartmentesId());
        platOrganizationDepartmentesUsersAddParam.setRole("2");
        platOrganizationDepartmentesUsersAddParam.setEnabled(1);
        platOrganizationDepartmentesUsersAddParam.setUserId(Long.parseLong(userId));
        platOrganizationDepartmentesUsersAddParam.setCreatedBy("系统自动生成");
        try {
            rs = usersService.savePlatformOrganizationDepartmentesUsers(platOrganizationDepartmentesUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门员工关联表异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门员工关联表异常" + e.getMessage());
        }
        return Response.data("新增成功");
    }

    /**
     * 分页获取供应商列表
     */
    @PostMapping(value = "/getPage4PlatformOrganization")
    @ApiOperation(value = "分页获取平台供应商列表")
    public Response getPage4PlatformOrganization(@RequestParam String pageNumber, @RequestParam String pageSize) {
        Response rs;
        try {
            PlatOrganizationQueryParam platOrganizationQueryParam = new PlatOrganizationQueryParam();
            platOrganizationQueryParam.setPageNumber(pageNumber);
            platOrganizationQueryParam.setPageSize(pageSize);
            rs = usersService.getPage(platOrganizationQueryParam);
        } catch (Exception e) {
            //log.error("分页获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("分页获取平台供应商信息列表" + e.getMessage());
        }
        return rs;
    }

    /**
     * 分页获取供应商列表
     */
    @PostMapping(value = "/getPage4PlatformOrganizationByStatus")
    @ApiOperation(value = "根据状态分页获取平台供应商列表")
    public Response<Page<PlatOrganizationQueryParam>> getPage4PlatformOrganizationByStatus(@RequestParam Integer status, @RequestParam String pageNumber, @RequestParam String pageSize) {
        Response<Page<PlatOrganizationQueryParam>> rs;
        try {
            PlatOrganizationQueryParam poQueryParam = new PlatOrganizationQueryParam();
            poQueryParam.setStatus(status);
            poQueryParam.setPageNumber(pageNumber);
            poQueryParam.setPageSize(pageSize);
            rs = usersService.getPage(poQueryParam);
        } catch (Exception e) {
            //log.error("分页获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据状态分页获取平台供应商列表" + e.getMessage());
        }
        return rs;
    }

    /**
     * 根据id查询供应商详情
     */
    @ApiOperation(value = "根据id查询")
    @ApiParam(name = "id", value = "主键ID", required = true)
    @GetMapping("/{id}")
    public Response selectPlatformOrganization(@PathVariable("id") @Valid Long id) {
        return usersService.selectPlatformOrganization(id);
    }

    /**
     * 根据id修改供应商审核状态status
     */
    @PutMapping(value = "/platApproval")
    @ApiOperation(value = "根据id修改平台供应商审核状态status")
    public Response<PlatOrganizationDTO> updateStatusByPlatformOrganizationId(@RequestParam Long id, @RequestParam Integer status) {
        Response response = usersService.platApproval(id, status);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("更新失败"));
        }
        return response;
    }

    /**
     * 平台供应商修改
     */
    @PutMapping("/updatePlatformOrganization")
    @ApiOperation(value = "修改平台供应商信息")
    public Response updatePlatformOrganization(@RequestBody PlatOrganizationUpdateParam Param) {
        Response response = usersService.update(Param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("更新失败"));
        }
        return response;
    }

    /**
     * 新增平台供应商部门
     */
    @PostMapping("/savePlatformOrganizationDepartmentes")
    @ApiOperation(value = "新增平台供应商部门")
    public Response savePlatformOrganizationDepartmentes(@RequestBody PlatOrganizationDepartmentesAddParam param) {
        if (param.getParentId() == null || param.getParentId() == 0L) {
            throw new ServiceException(CommonError.error("父id不能为空"));
        }
        Response response = usersService.savePlatformOrganizationDepartmentes(param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增平台供应商部门失败"));
        }
        return response;
    }


    /**
     * 手动添加平台供应商部门与人员关联表新增
     */
    @PostMapping("/savePlatformOrganizationDepartmentesUsers")
    @ApiOperation(value = "新增权限/新增平台供应商部门与人员关联表")
    public Response savePlatformOrganizationDepartmentesUsers(@RequestBody PlatOrganizationDepartmentesUsersAddParam param) {
        Response response = usersService.savePlatformOrganizationDepartmentesUsers(param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增平台供应商部门人员关联表失败"));
        }
        return response;
    }

}
